package com.open.admin.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.open.admin.entity.ResponseResult;
import com.open.admin.entity.User;
import com.open.admin.resp.LoginUser;
import com.open.admin.service.LoginService;
import com.open.admin.utils.JwtUtil;
import com.open.admin.utils.RedisCache;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult<Map<String,String>> login(User user) {
    	Map<String,String> map = new HashMap<>();
    	try {
	        //1. AuthenticationManager authenticate进行用户认证
	        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
	        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
	        //如果返回结果为null，则认证未通过，给出提示
	        if(Objects.isNull(authenticate)){
	            throw new RuntimeException("用户名或密码错误");
	        }
	        //使用userid生成token
	        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
	        String userId = loginUser.getUser().getId().toString();
	        String jwt = JwtUtil.createJWT(userId);
	        //authenticate存入redis
	        redisCache.setCacheObject("login:"+userId,loginUser);
	        //把token响应给前端
	        map.put("token",jwt);
	        map.put("avatar", loginUser.getUser().getAvatar());
	        map.put("userName", loginUser.getUser().getUserName());
	        map.put("nickName", loginUser.getUser().getNickName());
    	}catch (Exception e) {
			log.error("login", e);
		}
        return new ResponseResult<>(200,"登陆成功",map);
    }

    @Override
    public ResponseResult<String> logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        //删除redis中的value
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult<>(200,"注销成功");
    }
}